// 初始化脚本 - 清理和全局错误处理

// 清除可能的旧Three.js实例
if (typeof window !== 'undefined' && window.THREE) {
    console.warn('Detected existing THREE instance, clearing to prevent duplicate loading');
    delete window.THREE;
}

// 全局错误处理 - 过滤浏览器扩展错误
window.addEventListener('error', (event) => {
    if (event.message && event.message.includes('message channel closed')) {
        event.preventDefault();
        return;
    }
});

window.addEventListener('unhandledrejection', (event) => {
    const message = event.reason?.message || String(event.reason);
    const ignoredPatterns = [
        'message channel closed',
        'Extension context invalidated',
        'chrome-extension://',
        'moz-extension://'
    ];
    
    if (ignoredPatterns.some(pattern => message.includes(pattern))) {
        event.preventDefault();
        return;
    }
});

/**
 * 全局消息提示系统
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型: 'success', 'warning', 'error', 'info'
 * @param {number} duration - 显示时长（毫秒），默认3000ms
 */
window.showMessage = function(message, type = 'info', duration = 3000) {
    const container = document.getElementById('global-message-container');
    if (!container) {
        console.warn('消息容器未找到，无法显示消息:', message);
        return;
    }
    
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `global-message ${type}`;
    
    // 根据类型选择图标
    const icons = {
        success: '✅',
        warning: '⚠️',
        error: '❌',
        info: 'ℹ️'
    };
    
    messageEl.innerHTML = `
        <span class="global-message-icon">${icons[type] || icons.info}</span>
        <span class="global-message-text">${message}</span>
    `;
    
    // 添加到容器
    container.appendChild(messageEl);
    
    // 触发显示动画
    setTimeout(() => {
        messageEl.classList.add('show');
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        messageEl.classList.add('hiding');
        setTimeout(() => {
            messageEl.remove();
        }, 300);
    }, duration);
};

/**
 * 全局确认对话框
 * @param {string} message - 消息内容
 * @param {Object} options - 配置选项
 * @param {string} options.title - 对话框标题
 * @param {string} options.confirmText - 确认按钮文本
 * @param {string} options.cancelText - 取消按钮文本
 * @param {string} options.type - 类型: 'warning', 'danger', 'info'
 * @returns {Promise<boolean>} - 用户选择结果
 */
window.showConfirm = function(message, options = {}) {
    return new Promise((resolve) => {
        const {
            title = '确认操作',
            confirmText = '确定',
            cancelText = '取消',
            type = 'warning'
        } = options;
        
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'global-confirm-overlay';
        
        // 图标映射
        const icons = {
            warning: '⚠️',
            danger: '🗑️',
            info: 'ℹ️'
        };
        
        // 创建对话框
        overlay.innerHTML = `
            <div class="global-confirm-dialog ${type}">
                <div class="global-confirm-header">
                    <span class="global-confirm-icon">${icons[type] || icons.warning}</span>
                    <h3 class="global-confirm-title">${title}</h3>
                </div>
                <div class="global-confirm-body">
                    <p class="global-confirm-message">${message.replace(/\n/g, '<br>')}</p>
                </div>
                <div class="global-confirm-footer">
                    <button class="global-confirm-btn global-confirm-btn-cancel">${cancelText}</button>
                    <button class="global-confirm-btn global-confirm-btn-confirm ${type}">${confirmText}</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        
        // 触发显示动画
        setTimeout(() => overlay.classList.add('show'), 10);
        
        const dialog = overlay.querySelector('.global-confirm-dialog');
        const confirmBtn = overlay.querySelector('.global-confirm-btn-confirm');
        const cancelBtn = overlay.querySelector('.global-confirm-btn-cancel');
        
        // 处理确认
        const handleConfirm = () => {
            overlay.classList.remove('show');
            setTimeout(() => {
                overlay.remove();
                resolve(true);
            }, 200);
        };
        
        // 处理取消
        const handleCancel = () => {
            overlay.classList.remove('show');
            setTimeout(() => {
                overlay.remove();
                resolve(false);
            }, 200);
        };
        
        // 绑定事件
        confirmBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) handleCancel();
        });
        
        // ESC键取消
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                handleCancel();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);
        
        // 聚焦确认按钮
        setTimeout(() => confirmBtn.focus(), 100);
    });
};

/**
 * 全局输入对话框
 * @param {string} message - 提示消息
 * @param {string} defaultValue - 默认值
 * @param {Object} options - 配置选项
 * @returns {Promise<string|null>} - 用户输入的值或null
 */
window.showPrompt = function(message, defaultValue = '', options = {}) {
    return new Promise((resolve) => {
        const {
            title = '输入',
            confirmText = '确定',
            cancelText = '取消',
            placeholder = ''
        } = options;
        
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'global-confirm-overlay';
        
        // 创建对话框
        overlay.innerHTML = `
            <div class="global-confirm-dialog">
                <div class="global-confirm-header">
                    <span class="global-confirm-icon">✏️</span>
                    <h3 class="global-confirm-title">${title}</h3>
                </div>
                <div class="global-confirm-body">
                    <p class="global-confirm-message">${message.replace(/\n/g, '<br>')}</p>
                    <input type="text" class="global-prompt-input" value="${defaultValue}" placeholder="${placeholder}">
                </div>
                <div class="global-confirm-footer">
                    <button class="global-confirm-btn global-confirm-btn-cancel">${cancelText}</button>
                    <button class="global-confirm-btn global-confirm-btn-confirm">${confirmText}</button>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        
        // 触发显示动画
        setTimeout(() => overlay.classList.add('show'), 10);
        
        const input = overlay.querySelector('.global-prompt-input');
        const confirmBtn = overlay.querySelector('.global-confirm-btn-confirm');
        const cancelBtn = overlay.querySelector('.global-confirm-btn-cancel');
        
        // 处理确认
        const handleConfirm = () => {
            const value = input.value.trim();
            overlay.classList.remove('show');
            setTimeout(() => {
                overlay.remove();
                resolve(value || null);
            }, 200);
        };
        
        // 处理取消
        const handleCancel = () => {
            overlay.classList.remove('show');
            setTimeout(() => {
                overlay.remove();
                resolve(null);
            }, 200);
        };
        
        // 绑定事件
        confirmBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) handleCancel();
        });
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') handleConfirm();
        });
        
        // ESC键取消
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                handleCancel();
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);
        
        // 聚焦输入框并选中文本
        setTimeout(() => {
            input.focus();
            input.select();
        }, 100);
    });
};


/**
 * 向后兼容：覆盖浏览器原生对话框函数
 * 将所有alert、confirm、prompt自动使用自定义对话框
 */

// 保存原生函数的引用（用于调试）
window._nativeAlert = window.alert;
window._nativeConfirm = window.confirm;
window._nativePrompt = window.prompt;

// 覆盖 alert
window.alert = function(message) {
    // 使用自定义的showMessage，类型为warning以引起注意
    window.showMessage(message, 'warning', 4000);
};

// 覆盖 confirm - 显示警告但回退到原生对话框
window.confirm = function(message) {
    console.warn('⚠️ 检测到使用了confirm，建议改用异步的 await showConfirm(message, options)');
    console.warn('📖 查看迁移指南: /frontend-editor/DIALOG_MIGRATION_GUIDE.md');
    
    // 显示一个自定义消息提示用户应该迁移
    if (window.showMessage) {
        window.showMessage('检测到使用了浏览器原生确认框，建议升级为自定义对话框', 'info', 2000);
    }
    
    // 回退到原生confirm以不破坏现有功能
    return window._nativeConfirm(message);
};

// 覆盖 prompt - 显示警告但回退到原生对话框
window.prompt = function(message, defaultValue) {
    console.warn('⚠️ 检测到使用了prompt，建议改用异步的 await showPrompt(message, defaultValue, options)');
    console.warn('📖 查看迁移指南: /frontend-editor/DIALOG_MIGRATION_GUIDE.md');
    
    // 显示一个自定义消息提示用户应该迁移
    if (window.showMessage) {
        window.showMessage('检测到使用了浏览器原生输入框，建议升级为自定义对话框', 'info', 2000);
    }
    
    // 回退到原生prompt以不破坏现有功能
    return window._nativePrompt(message, defaultValue);
};
